/**
 * Copyright (c) 2017-2024 Nop Platform. All rights reserved.
 * Author: canonical_entropy@163.com
 * Blog:   https://www.zhihu.com/people/canonical-entropy
 * Gitee:  https://gitee.com/canonical-entropy/nop-entropy
 * Github: https://github.com/entropy-cloud/nop-entropy
 */
package com.gitee.wsl.text.marker

import com.gitee.wsl.func.Function
import kotlin.jvm.JvmOverloads

class MarkedString @JvmOverloads constructor(
    override val textSequence: String,
    override val markers: List<Marker> = emptyList()
) : IMarkedString {
    //val markers: List<Marker> = CollectionHelper.freezeList(markers)

    constructor(str: IMarkedString) : this(str.text, str.markers)

    override fun toString(): String {
        return this::class.simpleName + "[text=" + textSequence + ",markers=" + markers + "]"
    }

    override fun length(): Int {
        return textSequence.length
    }

    override val isEmpty: Boolean
        get() = textSequence.isEmpty()

    fun hasMarker(): Boolean {
        return markers.isNotEmpty()
    }

    val markerCount: Int
        get() = markers.size

    fun getMarker(index: Int): Marker {
        return markers[index]
    }

    val dumpText: String
        /**
         * 返回调试用的显示文本，所有的marker对应部分以及marker的内容将被显示出来
         */
        get() = renderText(Function { marker: Marker -> this.getMarkerDumpText(marker) })

    protected fun getMarkerDumpText(marker: Marker): StringBuilder {
        val sb= StringBuilder()
        sb.append('[').append(textSequence, marker.textBegin, marker.textEnd).append(']')
        sb.append("/*")
        sb.append(marker)
        sb.append("*/")
        return sb
    }

    companion object {

        val EMPTY: MarkedString = MarkedString("")
    }
}

fun MarkedString(builder:  MarkedStringBuilder.()->Unit): MarkedString {
    val sb = MarkedStringBuilder()
    sb.builder()
    return sb.end()
}